# -*- coding:UTF-8 -*-


from utils.image_code import image_code
from django_redis import get_redis_connection
from django.http import HttpResponse, JsonResponse
import pandas as pd
from work.models import *
import json


# 获取图片验证码
def get_image_code(request):
    if request.method == 'GET':
        code, code_image = image_code()
        # redis_cli = get_redis_connection('tools')
        request.session['code'] = code
        # print(code)
        # print(request.session.get('code'))
        return HttpResponse(code_image, content_type='image/png')


# 将条形码导出为csv格式
def export_passcode_to_csv(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    work_passcode = req_data["work_passcode"]
    csv_path = '/home/python/Desktop/%s' % work_passcode
    try:
        work = Work.objects.get(passcode=work_passcode)
    except Exception as e:
        data = {"success": False, "data": {"msg": "此订单号不存在!"}}
        return JsonResponse(data)
    goods = Goods.objects.filter(work=work)
    if len(goods) > 0:
        content_list = []
        for good in goods:
            cont_dict = {}
            cont_dict["商品名称"] = good.name
            cont_dict["拍摄许可码"] = good.code
            cont_dict["订单买家"] = good.work.name
            content_list.append(cont_dict)
        df = pd.DataFrame(content_list, columns=["商品名称", "拍摄许可码", "订单买家"])
        df.to_csv(csv_path, index=False)

        def file_iterator(file_name, chunk_size=5120):
            with open(file_name) as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield
                    else:
                        break
        response = HttpResponse(file_iterator(csv_path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="all_statements.csv"'
        # data = {"success": True, "data": {"msg": "导出数据成功!"}}
        return response

